package com.workingpub.commons.jdbc.builder.internal;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.workingpub.commons.jdbc.SqlDefineContext;
import com.workingpub.commons.jdbc.binding.IncludeEntry;
import com.workingpub.commons.jdbc.binding.SqlMapping;
import com.workingpub.commons.jdbc.builder.BuildContext;
import com.workingpub.commons.jdbc.builder.LogicResolver;
import com.workingpub.commons.jdbc.builder.ResolverFactory;

@Service
public class IncludeResolver implements LogicResolver {
	@Autowired
	private ResolverFactory resolverFactory;

	@Autowired
	private SqlDefineContext sqlDefineContext;

	@Override
	public List<Object> getContext(BuildContext buildContext, Object logicEntry) {
		if (logicEntry instanceof IncludeEntry) {
			IncludeEntry includeEntry = (IncludeEntry) logicEntry;
			Assert.isTrue(StringUtils.hasText(includeEntry.getRefid()), "The refrence sql id is null or empty.");
			SqlMapping sqlMapping = sqlDefineContext.getSqlMapping(includeEntry.getRefid());
			if (null != sqlMapping) {
				return resolverFactory.resolve(buildContext, sqlMapping.getContent().toArray());
			}
		}
		return null;
	}

}
